<?php


namespace app\api\controller\user;
use think\Controller;
use app\api\model\User as UserModel;
use app\api\model\DongTai;
use app\api\model\Dianzan;
use app\api\model\ShouChang;
use app\api\model\Address;
use app\api\model\GuanZhu;
use app\api\model\Order;
class User extends Controller
{
    public function login()
    {
        $msg = '';
        $code = -1;
        $userId = '';
        $sex = '0';
        $phone = input('phone');
        $password = input('password');
       if(!$phone){
           $msg = '请输入手机号';
       } else if(!$password)
       {
           $msg = '请输入密码';
       } else
       {
           //select 返回的数组不能用-> ,find返回的对象可以用->
           $user = UserModel::where('phone',$phone)->where('passwd',$password)->find();
           if(!$user)
           {
               $msg = '用户名或密码错误';
           } else
           {
               $userId=$user->id;
               $sex = $user->sex;
               $userName = $user->username;
               $avataUrl = $user->img_url;
               $bgImgUrl = $user->bgimg_url;
               $cosNumber = $user->cos_number;
               $msg = '登录成功';
               $code = '200';
               // 删除缓存数据
			   cache('uid', NULL);
			   // 设置缓存数据
			   cache('uid', $userId);
			    $response = [
		        	'info' => [
		        	'id' => $userId,
		        	'userName' => $userName,
		        	'avataUrl' => $avataUrl,
		        	'bgImgUrl' => $bgImgUrl,
		        	'sex' => $sex,
		        	'cosnumber' => $cosNumber,
		    		],
	            'id' => $userId,
	            'code' => $code,
	            'msg' => $msg,
    		 ];
    		return json($response);
           }
       }
//        $user = UserModel::get('1');
//        return json($user->toArray());
        $response = [
            'code' => $code,
            'msg' => $msg,
        ];
       return json($response);
    }
    public function reg()
    {
        $userId = '';
        $avataUrl = '';
        $phone = input('phone');
        $password = input('password');
        $userName = input('username');
        $sex = input('sex');
        $file =request()->file('file');
        $avataFile =$file[0];
        $cos_number = '5201314';
        // 如果没有上传图像那么采用默认图像
       if(!$phone){
           $msg = '请输入手机号';
       } else if(!$password)
       {
           $msg = '请输入密码';
       } else {
     //  	echo 'phone is:'.$phone.'<br/>';
   		// echo 'password is:'.$password.'<br/>';
   		// echo 'userName is:'.$username.'<br/>';
   		if(!$avataFile) {
        	$avataUrl = 'http://112.126.100.206/userdata/avatars/default-avatar.png';
        } else {
    		$info = $avataFile->rule('uniqid')->move('/userdata/avatars/');
   			$avataUrl='http://112.126.100.206/userdata/avatars/'.$info->getSaveName();	
        }
   		$user = UserModel::getByUsername($userName);
   		if($user)
   		{
   			$response = [
            'code' => -1,
            'msg' => '用户名已经被注册',
        	];
    		return json($response);
   		}
   		$user = UserModel::getByPhone($phone);
   		if($user)
   		{
   			$response = [
            'code' => -1,
            'msg' => '手机号已经被注册',
        	];
    		return json($response);
   		}
   		// 如果走到这里说明上面的条件都没满足，说明可以注册
   		$user = new UserModel();
   		$user->username = $userName;
   		$user->passwd = $password;
   		$user->phone =$phone;
   		$user->sex = $sex;
   		$user->img_url = $avataUrl;
   		// 生成10位的cos数 年月日6位加上随机的4位数
   		$seed = time();                   // 使用时间作为种子源
		mt_srand($seed);                  // 播下随机数发生器种子
	    $number = rand(1000, 9999);      // 根据种子生成 1000000~9999999 之间的随机数，如果 $seed 值固定，则生成的随机数也不变
   		$datatime = date('Y-m-d', time()).'';
   		$datatime = join('',explode('-',$datatime));
   	    $cosNumber = $datatime.$number;
   	    $user->cos_number = $cosNumber;
   		$user->save();
   		$userId = $user->id;
   		
   	    // 删除缓存数据 
	   cache('uid', NULL);
	   // 设置缓存数据,保存登录的用户id
	   cache('uid', $userId);
   		$response = [
        'code' => 200,
        'id' => $userId,
        'info' => [
        	'id' => $userId,
        	'userName' => $userName,
        	'avataUrl' => $avataUrl,
        	'sex' => $sex,
        	'cosnumber' => $cosNumber,
    	],
        'msg' => '注册成功',
    	];
		return json($response);
       }
    }
    public function loginout()
    {
    	// 删除会话id，用来登出
    	cache('uid', null);
    	$response = [
            'code' => 200,
            'msg' => '登出成功',
        	];
    		return json($response);
    }
    public function addaddress() {
    	$name = input('name');
    	$userId = input('userId');
    	$phone = input('phone');
    	$province = input('province');
    	$city = input('city');
    	$county = input('county');
    	$taddress = input('address');
    	$default = input('default');
    	if($default==1) {
    		// 如果用户将这条设为默认地址那么删除以前的默认地址
    		$address = Address::where('default', 1)->where('user_id',$userId)->find();
			if($address) {
				$address->default = 0;
    			$address->save();
			}
    	}
    	$address = new Address();
    	$address->name = $name;
    	$address->user_id = $userId;
    	$address->phone = $phone;
    	$address->province = $province;
    	$address->city = $city;
    	$address->county = $county;
    	$address->address = $taddress;
    	$address->default = $default;
    	$result = $address->save();
		if($result) {
			$res = [
			"code" => 200,
			'msg' => '新建收货地址成功'
			];
			return json($res);
		} else {
			$res = [
			"code" => -1,
			'msg' => '新建收货地址失败'
			];
			return json($res);
		}
    }
    public function getAddress() {
    	$userId = input('userId');
    	$data = [];
    	$addressArray = Address::where('user_id', $userId)->select();
    	foreach ($addressArray as $address) {
    		$temp = [
    			'name'=> $address->name,
		        'userId'=>  $address->user_id,
		        'phone'=>$address->phone,
		        'province'=> $address->province,
		        'city'=>$address->city,
		        'county' => $address->county,
		        'address'=>$address->address,
		        'default'=>$address->default,
    		];
    		array_push($data,$temp);
    	}
    	$res = [
    		'data' => $data,
    		'code' => 200,
    		'msg' => '获取地址成功'
    		];
    	return json($res);
    }
    public function addOrder() {
    	$userId = input('userId');
    	$pid = input('pid');
    	$reserveName = input('reserveName');
    	$phone = input('phone');
    	$productName = input('productName');
    	$style = input('style');
    	$size = input('size');
    	$yunfei = input('yunfei');
    	$price = input('price');
    	$buyNumber = input('buyNumber');
    	$totalPrice = input('totalPrice');
    	$message = input('message');
    	$province = input('province');
    	$city = input('city');
    	$county = input('county');
    	$address = input('address');
    	$allAddress = input('allAddress');
    	$payway = input('payway');
    	$orderNumber = input('orderNumber');
	    $data = [
	    	'user_id' => $userId,
	    	'product_id' => $pid,
	    	'reserveName' => $reserveName,
	    	'phone'=> $phone,
	    	'productName' => $productName,
	    	'style' => $style,
	    	'size' => $size,
	    	'yunfei' => $yunfei,
	    	'price' => $price,
	    	'buyNumber' => $buyNumber,
	    	'totalPrice' => $totalPrice,
	    	'message' => $message,
	    	'province' => $province,
	    	'city' => $city,
	    	'county' => $county,
	    	'address'=> $address,
	    	'allAddress' => $allAddress,
	    	'payway' => $payway,
	    	'orderNumber' => $orderNumber,
	    	];
    	$order = new Order();
    	$result = $order->save($data);
    	if($result) {
    		$res = [
			'code' => 200,
			'msg' => '下单成功，系统正在审核'
    		];
    		return json($res);
    	} else {
			$res = [
			'code' => -1,
			'msg' => '未知错误'
    		];
    		return json($res);
    	}
    	return 0;
    }
    public function delSelfDongTai() {
    	$userId = input('userId');
    	$did = input('did');
    	$dongtai = DongTai::where('user_id',$userId)->where('id',$did);
    	if($dongtai)
    	{
    		$dongtai->delete();
    		$res = [
    			'code' => 200,
    			'msg' => '删除成功'
    			];
			return json($res);
    	} else {
    		$res = [
    			'code' => -1,
    			'msg' => '改动态不存在或者以删除'
    			];
			return json($res);
    	}
    }
    public function getUserDetail () {
    	$userId = input('userId');
    	$user = UserModel::get($userId);
    	if($user) {
    		 $name = $user->username;
    		 $sex = $user->sex;
    		 $cosnumber = $user->cos_number;
    		 $sign = $user->sign;
    		 $province = $user->province;
    		 $city = $user->city;
    		 $fansNumber = GuanZhu::where('gzuser_id', $user->id)->count('gzuser_id');
    		 $guanzhuNumber = GuanZhu::where('user_id', $user->id)->count('user_id');
    		 //$fansNumber = $user->fansnumber;
    		 //$guanzhuNumber = $user->guanzhunumber;
    		 $renqiNumber = DongTai::where('user_id', $user->id)->sum('dnumber')+DongTai::where('user_id', $user->id)->sum('snumber')+DongTai::where('user_id', $user->id)->sum('pnumber');
    		 $avataUrl = $user->img_url;
    		 $bgimgUrl = $user->bgimg_url;
    		 $res = [
    		 		'code' => 200,
    		 		'msg' => '查询成功',
    		 		'data' => 
    		 		[
    		 			'name' => $name,
		    		 	'sex' => $sex,
		    		 	'cosNumber' => $cosnumber,
		    		 	'sign' => $sign,
		    		 	'province' => $province,
		    		 	'city' => $city,
		    		 	'avatarUrl' => $avataUrl,
		    		 	'bgImgUrl' => $bgimgUrl,
		    		 	'fansNumber' => $fansNumber,
		    		 	'guanZhuNumber' => $guanzhuNumber,
		    		 	'popularity' => $renqiNumber,
    		 		],
    		 	];
    		 	return json($res);
    	}
    	dump($user);
    	return 0;
    }
    // 获得用户动态
    public function getUserDongTai() {
    	$page = input('page');
        $mySelfId = input('userId'); // 获得登录的用户id
        $scene = input('scene'); // 保存场景，release是发布的数据，liked是赞过的数据
        $data = [];
        if($scene === "liked")
        {
        	// 获取用户点赞过的的动态
        	// echo "请求获取赞过的数据";
        	$dianzan = Dianzan::where('user_id', $mySelfId)->paginate(10,true);
        	foreach ($dianzan as $value) 
        	{
        		$dongtai = DongTai::get($value->dongtai_id); // 获取此条动态
        		if(!$dongtai) {
        			continue;
        		}
        		$user = UserModel::get($mySelfId);
        		$tempSC = ShouChang::where('dongtai_id', $value->dongtai_id)->where('user_id', $mySelfId)->find();
        		$inShouChang = 0; // 默认不在收藏里面
	            if($tempSC) {$inShouChang = 1;}
	            $inDianZan = 1;
	            $info = [
	            	'user_id'=> $dongtai->user_id,
	                'img' => $user->img_url,
	                'name' => $user->username,
	                'sex' => $user->sex,
	                'time' => $dongtai->create_time
	            ];
	            $temp = [
		        	'info' => $info,
					'create_time' => $dongtai->create_time,
	                'did' => $dongtai->id,
	                'user_id'=> $dongtai->user_id,
	                'content' =>  $dongtai->content,
	                'labels' => explode(';',$dongtai->labels),
	                'dianzan'=> $dongtai->dnumber,
	                'pinglun'=> $dongtai->pnumber,
	                'shoucang'=> $dongtai->snumber,
	                'urls' => explode(';',$dongtai->url),
	                'type'=> $dongtai->type,
	                'indianzan' => $inDianZan,
	                'inshouchang'=> $inShouChang,
	            ];
	            array_push($data,$temp); //保存全部保存刷新帮助
        	} // end foreach
        	 $res = [
	            'msg' => '查询成功',
	            'code' => 200,
	            'data'=> $data,
	        ];
	        return json($res);
        } else 
        {
        // 获取用户自己发布的动态
	        $dongtai = DongTai::where('user_id', $mySelfId)->order('create_time desc')->paginate(10,true);
	        $data = [];
		     foreach ($dongtai as $value){
		        $user = UserModel::get($value->user_id); // 获得这个id所属的用户
		        $inDianZan = 0; //  默认不在点赞里面
		        $inShouChang = 0; // 默认不在此条动态的收藏里面
		        if($mySelfId) 
		        {
		          // 如果用户id没传也不会引起报错
		          // 登录用户是否点赞过该数据
		           $tempDZ = Dianzan::where('dongtai_id', $value->id)->where('user_id', $mySelfId)->find();
		           if($tempDZ) {$inDianZan = 1;}
		           // 登录用户是否收藏过该数据
		           $tempSC = ShouChang::where('dongtai_id', $value->id)->where('user_id', $mySelfId)->find();
		           if($tempSC) {$inShouChang = 1;}
		        }
		         $info = [
	            	'user_id'=> $value->user_id,
	                'img' => $user->img_url,
	                'name' => $user->username,
	                'sex' => $user->sex,
	                'time' => $value->create_time
	            ];
		        $temp = [
		        	'info' => $info,
					'create_time' => $value->create_time,
	                'did' => $value->id,
	                'user_id'=> $value->user_id,
	                'content' =>  $value->content,
	                'labels' => explode(';',$value->labels),
	                'dianzan'=> $value->dnumber,
	                'pinglun'=> $value->pnumber,
	                'shoucang'=> $value->snumber,
	                'urls' => explode(';',$value->url),
	                'type'=> $value->type,
	                'indianzan' => $inDianZan,
	                'inshouchang'=> $inShouChang,
	            ];
	            array_push($data,$temp); //保存全部保存刷新帮助
		     } // end foreach
		     $res = [
	            'msg' => '查询成功',
	            'code' => 200,
	            'data'=> $data,
	        ];
	        return json($res);
        }
    }
    // 增加关注
    public function addGuanZhu()
    {
    	$userId = input('userId'); // 获得当前用户
    	$guid = input('gzuserId'); // 关注的哪个用户
    	if($userId == $guid)
    	{
    		$res = [
    		'code' =>-1,
    		'msg' => '不能关注您自己哦(*^▽^*)',
    		];
    	return json($res);
    	}
    	$guanzhu = GuanZhu::where('user_id',$userId)->where('gzuser_id',$guid)->find();
    	if($guanzhu)
    	{
    		$res = ['code'=>-1, 'msg'=> '您已经关注过此用户'];
			return json($res);	
    	}
    	$guanzhu = new GuanZhu();
    	$guanzhu->user_id = $userId;
    	$guanzhu->gzuser_id = $guid;
    	$guanzhu->save();
    	$res = [
    		'code' =>200,
    		'msg' => '关注成功',
    		];
    	return json($res);
    }
    // 取消关注
    public function cancleGuanZhu()
    {
    	$userId = input('userId');
    	$guid = input('gzuserId'); // 取消关注哪个用户
    	$guanzhu = GuanZhu::where('user_id',$userId)->where('gzuser_id',$guid)->find();
    	// $result = $guanzhu->delete();
    	if($guanzhu) 
		{   
			// 如果动态存在在进行操作
			$guanzhu->delete();
			$res = ['code'=>200, 'msg'=> '取消关注成功'];
			return json($res);
		} else {
			$res = ['code'=>-1, 'msg'=> '您还没有关注此用户'];
			return json($res);
		}
    }
    // 获得关注列表
    public function getGuanZhuList() {
    	$userId = input('userId');
    	$guanzhus = GuanZhu::where('user_id',$userId)->paginate(10,true);
    	$data = [];
    	foreach($guanzhus as $value) 
    	{
    		$user = UserModel::get($value->gzuser_id);
    		$temp= [
    			'userId' => $user->id,
    			'name' => $user-> username,
    			'avatarUrl' => $user->img_url,
    			'sex' => $user->sex,
    			'sign' => $user->sign,
    			];
			array_push($data,$temp);
    	}
    	$res = [
    		'code' => 200,
    		'data' =>$data,
    		];
    	// dump($data);
    	return json($res);
    }
    public function getFansList()
    {
		$userId = input('userId');
    	$guanzhus = GuanZhu::where('gzuser_id',$userId)->paginate(10,true);
    	$data = [];
    	foreach($guanzhus as $value) 
    	{
    		$user = UserModel::get($value->user_id);
    		$temp= [
    			'userId' => $user->id,
    			'name' => $user-> username,
    			'avatarUrl' => $user->img_url,
    			'sex' => $user->sex,
    			'sign' => $user->sign,
    			];
			array_push($data,$temp);
    	}
    	$res = [
    		'code' => 200,
    		'data' =>$data,
    		];
    	// dump($data);
    	return json($res);
    }
    // 更新用户信息
    public function updateUserInfo() {
    	$id = input('userId');
    	$name = input ('name');
    	$sex = input('sex');
    	$province = input('province');
    	$sign = input('sign');
    	$city = input('city');
    	$file =request()->file('file');
        $avataFile =$file[0];
    	$user = UserModel::get($id);
    	$avataUrl = '';
		if($avataFile)
	    {
   			$info = $avataFile->rule('uniqid')->move('/userdata/avatars/');
   			$avataUrl='http://112.126.100.206/userdata/avatars/'.$info->getSaveName();
	    } else {
	    	$avataUrl = $user->img_url;
	    }
	    $data = [
    		'id' => $id,
    		'username' => $name,
    		'sex' => $sex,
    		'province' => $province,
    		'city' => $city,
    		'sign' => $sign,
    		'img_url' => $avataUrl
    		];
    	$result = $user->save($data);
    	if($result)
    	{
    		$res = [
            'msg' => '成功',
            'code' => 200,
        	];
        	return json($res);
		} else {
			$res = [
            'msg' => '失败',
            'code' => -1,
        	];
        	return json($res);
		}
    }
}